﻿#coding=utf-8
#Boa:FramePanel:PanelOrderPurchase

import wx
import wx.grid

import DlgPopupSupplier
import DlgSelectPro
import DlgProGX

from product import *
from ctrlAider import *
from MyListCtrl import *
import config

import dbmngr
import kit

[wxID_PANELORDERPURCHASE, wxID_PANELORDERPURCHASEBTNADDPRO, 
 wxID_PANELORDERPURCHASEBTNCANCEL, wxID_PANELORDERPURCHASEBTNDELPRO, 
 wxID_PANELORDERPURCHASEBTNHISTORY, wxID_PANELORDERPURCHASEBTNNEWPRO, 
 wxID_PANELORDERPURCHASEBTNSAVE, wxID_PANELORDERPURCHASEBTNSHOWCUSTOMER, 
 wxID_PANELORDERPURCHASECOMBOBOX_STAFF, wxID_PANELORDERPURCHASEDATESO, 
 wxID_PANELORDERPURCHASEGRIDSOPROLIST, wxID_PANELORDERPURCHASESTATICBOX1, 
 wxID_PANELORDERPURCHASESTATICTEXT1, wxID_PANELORDERPURCHASESTATICTEXT2, 
 wxID_PANELORDERPURCHASESTATICTEXT3, wxID_PANELORDERPURCHASESTATICTEXT4, 
 wxID_PANELORDERPURCHASESTATICTEXT_CUST, 
 wxID_PANELORDERPURCHASESTATICTEXT_DATE, 
 wxID_PANELORDERPURCHASESTATICTEXT_MEMO, 
 wxID_PANELORDERPURCHASESTATICTEXT_SHISHOU, 
 wxID_PANELORDERPURCHASESTATICTEXT_SOID, 
 wxID_PANELORDERPURCHASESTATICTEXT_STAFF, 
 wxID_PANELORDERPURCHASESTATICTEXT_YINGSHOU, 
 wxID_PANELORDERPURCHASESTATICTEXT_YOUHUI, wxID_PANELORDERPURCHASETCCUSTOMER, 
 wxID_PANELORDERPURCHASETCMEMO, wxID_PANELORDERPURCHASETCPAID, 
 wxID_PANELORDERPURCHASETCSHISHOU, wxID_PANELORDERPURCHASETCTOTAL, 
 wxID_PANELORDERPURCHASETCUNPAID, wxID_PANELORDERPURCHASETCYINGSHOU, 
 wxID_PANELORDERPURCHASETCYOUHUI, wxID_PANELORDERPURCHASETSOID, 
] = [wx.NewId() for _init_ctrls in range(33)]

class PanelOrderPurchase(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELORDERPURCHASE,
              name=u'PanelOrderPurchase', parent=prnt, pos=wx.Point(1, 27),
              size=wx.Size(1282, 647), style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(1274, 613))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.staticText1 = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT1,
              label=u'\u5546\u54c1\u5165\u5e93', name='staticText1',
              parent=self, pos=wx.Point(240, 32), size=wx.Size(84, 20),
              style=0)
        self.staticText1.SetFont(wx.Font(15, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, u'\u6977\u4f53_GB2312'))

        self.staticText_SOID = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_SOID,
              label=u'\u5355\u53f7\uff1a', name=u'staticText_SOID', parent=self,
              pos=wx.Point(408, 48), size=wx.Size(64, 14), style=0)

        self.TSOID = wx.StaticText(id=wxID_PANELORDERPURCHASETSOID,
              label=u'CG-20150101-00001', name=u'TSOID', parent=self,
              pos=wx.Point(472, 48), size=wx.Size(162, 16), style=0)
        self.TSOID.Show(False)

        self.dateSO = wx.DatePickerCtrl(id=wxID_PANELORDERPURCHASEDATESO,
              name=u'dateSO', parent=self, pos=wx.Point(472, 88),
              size=wx.Size(136, 22), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
        self.dateSO.SetLabel(u'2013-11-27')
        self.dateSO.SetValue(wx.DateTimeFromDMY(27, 10, 2013, 0, 0, 0))
        self.dateSO.SetWindowVariant(wx.WINDOW_VARIANT_NORMAL)
        self.dateSO.Bind(wx.EVT_DATE_CHANGED, self.OnDateChanged,
              id=wxID_PANELORDERPURCHASEDATESO)

        self.staticBox1 = wx.StaticBox(id=wxID_PANELORDERPURCHASESTATICBOX1,
              label=u'', name='staticBox1', parent=self, pos=wx.Point(64, 72),
              size=wx.Size(552, 56), style=0)
        self.staticBox1.SetBackgroundColour(wx.Colour(200, 208, 253))

        self.staticText_date = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_DATE,
              label=u'\u65e5\u671f\uff1a', name=u'staticText_date', parent=self,
              pos=wx.Point(408, 96), size=wx.Size(56, 14), style=0)

        self.btnShowCustomer = wx.Button(id=wxID_PANELORDERPURCHASEBTNSHOWCUSTOMER,
              label=u'+', name=u'btnShowCustomer', parent=self,
              pos=wx.Point(328, 88), size=wx.Size(32, 26), style=0)
        self.btnShowCustomer.Bind(wx.EVT_BUTTON, self.OnBtnShowCustomerButton,
              id=wxID_PANELORDERPURCHASEBTNSHOWCUSTOMER)

        self.TCCustomer = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCCUSTOMER,
              name=u'TCCustomer', parent=self, pos=wx.Point(144, 88),
              size=wx.Size(176, 26), style=0, value=u'')

        self.staticText_cust = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_CUST,
              label=u'\u4f9b\u8d27\u5546\uff1a', name=u'staticText_cust',
              parent=self, pos=wx.Point(72, 88), size=wx.Size(68, 16), style=0)

        self.gridSOProList = wx.grid.Grid(id=wxID_PANELORDERPURCHASEGRIDSOPROLIST,
              name=u'gridSOProList', parent=self, pos=wx.Point(64, 192),
              size=wx.Size(652, 224), style=wx.STATIC_BORDER)
        self.gridSOProList.SetHelpText(u'')
        self.gridSOProList.SetLabel(u'gridSOProList')
        self.gridSOProList.SetToolTipString(u'gridSOProList')
        self.gridSOProList.SetWindowVariant(wx.WINDOW_VARIANT_LARGE)
        self.gridSOProList.SetColLabelSize(32)
        self.gridSOProList.SetRowLabelSize(20)
        self.gridSOProList.SetColMinimalAcceptableWidth(0)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_CELL_CHANGE,
              self.OnGridSOProListGridCellChange)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_SELECT_CELL,
              self.OnGridSOProListGridSelectCell)
        self.gridSOProList.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK,
              self.OnGridSOProListGridCellRightClick)

        self.staticText_YingShou = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_YINGSHOU,
              label=u'\u5e94\u4ed8\u91d1\u989d\uff1a',
              name=u'staticText_YingShou', parent=self, pos=wx.Point(72, 440),
              size=wx.Size(85, 16), style=0)

        self.tcYingShou = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCYINGSHOU,
              name=u'tcYingShou', parent=self, pos=wx.Point(160, 432),
              size=wx.Size(80, 22), style=0, value=u'0.0')
        self.tcYingShou.SetEditable(False)
        self.tcYingShou.Enable(False)

        self.staticText_shishou = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_SHISHOU,
              label=u'\u5b9e\u4ed8\u91d1\u989d\uff1a',
              name=u'staticText_shishou', parent=self, pos=wx.Point(256, 440),
              size=wx.Size(85, 16), style=0)

        self.tcShiShou = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCSHISHOU,
              name=u'tcShiShou', parent=self, pos=wx.Point(344, 432),
              size=wx.Size(84, 22), style=0, value=u'0.0')
        self.tcShiShou.SetEditable(False)
        self.tcShiShou.Enable(False)

        self.staticText_YouHui = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_YOUHUI,
              label=u'\u4f18\u60e0\u91d1\u989d\uff1a',
              name=u'staticText_YouHui', parent=self, pos=wx.Point(440, 440),
              size=wx.Size(85, 16), style=0)

        self.tcYouHui = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCYOUHUI,
              name=u'tcYouHui', parent=self, pos=wx.Point(528, 432),
              size=wx.Size(88, 22), style=0, value=u'0.0')
        self.tcYouHui.SetEditable(True)
        self.tcYouHui.Enable(True)

        self.btnSave = wx.Button(id=wxID_PANELORDERPURCHASEBTNSAVE,
              label=u'\u4fdd\u5b58\u8ba2\u5355', name=u'btnSave', parent=self,
              pos=wx.Point(520, 480), size=wx.Size(93, 26), style=0)
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnBtnSaveButton,
              id=wxID_PANELORDERPURCHASEBTNSAVE)

        self.comboBox_staff = wx.ComboBox(choices=[],
              id=wxID_PANELORDERPURCHASECOMBOBOX_STAFF, name=u'comboBox_staff',
              parent=self, pos=wx.Point(160, 480), size=wx.Size(146, 24),
              style=wx.CB_READONLY, value=u'')
        self.comboBox_staff.SetLabel(u'')

        self.staticText_staff = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_STAFF,
              label=u'\u7ecf\u624b\u4eba\uff1a', name=u'staticText_staff',
              parent=self, pos=wx.Point(72, 480), size=wx.Size(72, 14),
              style=0)

        self.staticText_memo = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT_MEMO,
              label=u'\u5907\u6ce8\uff1a', name=u'staticText_memo', parent=self,
              pos=wx.Point(72, 520), size=wx.Size(72, 14), style=0)

        self.tcMemo = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCMEMO,
              name=u'tcMemo', parent=self, pos=wx.Point(160, 520),
              size=wx.Size(352, 48), style=wx.TE_MULTILINE, value=u'')

        self.btnCancel = wx.Button(id=wxID_PANELORDERPURCHASEBTNCANCEL,
              label=u'\u9000\u51fa', name=u'btnCancel', parent=self,
              pos=wx.Point(520, 544), size=wx.Size(93, 26), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_PANELORDERPURCHASEBTNCANCEL)

        self.btnHistory = wx.Button(id=wxID_PANELORDERPURCHASEBTNHISTORY,
              label=u'\u5f80\u6765\u5355\u636e', name=u'btnHistory',
              parent=self, pos=wx.Point(736, 40), size=wx.Size(88, 26),
              style=0)
        self.btnHistory.Bind(wx.EVT_BUTTON, self.OnBtnHistoryButton,
              id=wxID_PANELORDERPURCHASEBTNHISTORY)

        self.TCTotal = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCTOTAL,
              name=u'TCTotal', parent=self, pos=wx.Point(824, 80),
              size=wx.Size(88, 24), style=0, value=u'0.0')
        self.TCTotal.SetEditable(False)
        self.TCTotal.SetInsertionPoint(0)
        self.TCTotal.Enable(True)

        self.staticText2 = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT2,
              label=u'\u5e94\u6536\u91d1\u989d\uff1a', name='staticText2',
              parent=self, pos=wx.Point(736, 88), size=wx.Size(85, 16),
              style=0)

        self.staticText3 = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT3,
              label=u'\u5df2\u6536\u91d1\u989d\uff1a', name='staticText3',
              parent=self, pos=wx.Point(736, 112), size=wx.Size(85, 16),
              style=0)

        self.TCPaid = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCPAID,
              name=u'TCPaid', parent=self, pos=wx.Point(824, 104),
              size=wx.Size(88, 24), style=0, value=u'0.0')
        self.TCPaid.SetEditable(False)
        self.TCPaid.Enable(True)

        self.TCUnpaid = wx.TextCtrl(id=wxID_PANELORDERPURCHASETCUNPAID,
              name=u'TCUnpaid', parent=self, pos=wx.Point(824, 128),
              size=wx.Size(88, 24), style=wx.TE_READONLY, value=u'0.0')
        self.TCUnpaid.SetForegroundColour(wx.Colour(255, 0, 0))
        self.TCUnpaid.SetEditable(False)
        self.TCUnpaid.Enable(True)
        self.TCUnpaid.SetBackgroundColour(wx.Colour(255, 255, 255))

        self.staticText4 = wx.StaticText(id=wxID_PANELORDERPURCHASESTATICTEXT4,
              label=u'\u672a\u6536\u91d1\u989d\uff1a', name='staticText4',
              parent=self, pos=wx.Point(736, 136), size=wx.Size(85, 16),
              style=0)

        self.btnAddPro = wx.Button(id=wxID_PANELORDERPURCHASEBTNADDPRO,
              label=u'\u8001\u5546\u54c1\u6dfb\u52a0', name=u'btnAddPro',
              parent=self, pos=wx.Point(64, 152), size=wx.Size(93, 26),
              style=0)
        self.btnAddPro.Bind(wx.EVT_BUTTON, self.OnMenuAdd,
              id=wxID_PANELORDERPURCHASEBTNADDPRO)

        self.btnNewPro = wx.Button(id=wxID_PANELORDERPURCHASEBTNNEWPRO,
              label=u'\u65b0\u5546\u54c1\u6dfb\u52a0', name=u'btnNewPro',
              parent=self, pos=wx.Point(176, 152), size=wx.Size(93, 26),
              style=0)
        self.btnNewPro.Bind(wx.EVT_BUTTON, self.OnMenuNewPro,
              id=wxID_PANELORDERPURCHASEBTNNEWPRO)

        self.btnDelPro = wx.Button(id=wxID_PANELORDERPURCHASEBTNDELPRO,
              label=u'\u5220\u9664\u9009\u4e2d\u5546\u54c1', name=u'btnDelPro',
              parent=self, pos=wx.Point(288, 152), size=wx.Size(112, 26),
              style=0)
        self.btnDelPro.Bind(wx.EVT_BUTTON, self.OnMenuDelRow,
              id=wxID_PANELORDERPURCHASEBTNDELPRO)

    def __init__(self, parent):
        self._init_ctrls(parent)

        self.myInit()
        
    def myInit(self):       
        # supplier
        self.m_peer = None
        self.TCCustomer.SetFocus()
        
        # state matchine
        self.myInitState()
        
        # Set to Today
        self.dateSO.SetValue(wx.DateTime.Today())
        self.refreshBillId()
        
        # grid
        self.myInitGrid()
        
        #经手人
        self.cbHandler = MyComboBoxDecorator(self.comboBox_staff, CDataStaff, CDataStaff.COL_NAME)
        self.cbHandler.refresh()
        self.cbHandler.SetValue(config.Cfg.getCurUser().getValue(CDataStaff.COL_NAME))

        
        
        self.myInitPWin()
        
        #设置曾经购买的产品列表
        self.lcHistory = MyListCtrlSupplierProRecent(self, pos=wx.Point(736, 176),
                                                    size=wx.wx.Size(400, 350))
        #self.lcHistory.SetSize(wx.Size(400, 350))
        #self.lcHistory.Move(wx.Point(760, 200))
        self.lcHistory.Bind(wx.EVT_LEFT_DCLICK, self.OnLcHistoryProLeftDclick)

    def myInitPWin(self):
        self.pWin = DlgPopupSupplier.create(self)
        self.tcPeer = MyPopupTextCtrlDecorator(self.TCCustomer, self.pWin)
           
    def myInitState(self):
        self.STATE_NEW = 0
        self.STATE_MODIFY = 1
        self.curState = self.STATE_NEW #default state
        self.editedBillId = ''
        self.bSaved = False
    
    def isModify(self):
        return self.curState == self.STATE_MODIFY
    
    def myInitGrid(self):
        titles = [(u'编号', 0),
                    (u'产品', 160), 
                    (u'规格', 0), 
                    (u'单位', 50), 
                    (u'数量', 70), 
                    (u'单价',70), 
                    (u'小计',100),
                    (u'备注',170)]
        [self.COL_PROID , self.COL_PRONAME, self.COL_PROSPEC, self.COL_UNIT, self.COL_CNT,
        self.COL_PRICE, self.COL_TOTAL,self.COL_MEMO] = [i for i in range(len(titles))]
         
        self.gridSOProList.CreateGrid(0, len(titles))
        for i in range(len(titles)):
            self.gridSOProList.SetColLabelValue(i, titles[i][0])
            self.gridSOProList.SetColSize(i, titles[i][1])
        self.gridSOProList.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        
        attr = wx.grid.GridCellAttr()
        attr.SetReadOnly(True)
        attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        attr.SetBackgroundColour(wx.LIGHT_GREY)
        self.gridSOProList.SetColAttr(self.COL_PROID, attr)
        self.gridSOProList.SetColAttr(self.COL_UNIT, attr)
        self.gridSOProList.SetColAttr(self.COL_TOTAL, attr)
        self.gridSOProList.SetColAttr(self.COL_PROSPEC, attr)

        attr = wx.grid.GridCellAttr()
        attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.gridSOProList.SetColAttr(self.COL_CNT, attr)
        self.gridSOProList.SetColAttr(self.COL_PRICE, attr)
        #self.gridSOProList.SetColAttr(self.COL_TOTAL, attr)
        
        
        #添加右键菜单
        self.menu = wx.Menu()
        
        item = self.menu.Append(-1, u'添加已有商品')
        self.Bind(wx.EVT_MENU, self.OnMenuAdd, item)
        
        item = self.menu.Append(-1, u'添加新商品')
        self.Bind(wx.EVT_MENU, self.OnMenuNewPro, item)
        
        item = self.menu.Append(-1, u'删除选中行')
        self.Bind(wx.EVT_MENU, self.OnMenuDelRow, item)

        self.gridSOProList.GetGridWindow().Bind(wx.EVT_RIGHT_UP, self.OnGridRightUp)
        
    def refreshBillId(self):
        if self.isModify():
            # 150902 编辑模式禁止修改ID，否则ID变化会导致相关表要求同步修改，复杂度高，健壮性差
            return
        
        #date = self.dateSO.GetValue().Format('%Y%m%d')
        #id = CDataPurOrder.newBillId(date)
        #self.TSOID.SetLabel(id)
    
    def refreshAmount(self):
        amount = 0
        for i in range(self.gridSOProList.GetNumberRows()):
            amount += float(self.gridSOProList.GetCellValue(i, self.COL_TOTAL))
 
        self.tcYingShou.SetValue(str(amount))
        
    def setSelectPeer(self, obj):
        self.m_peer = obj
     
        name = self.m_peer.getValue(self.m_peer.COL_NAME)
        self.tcPeer.ChangeValue(name)
        
        title = u'【购】%s' %name
        #self.SetTitle(title)
        book = self.GetParent()
        self.GetParent().SetPageText(book.GetSelection(), title)
        
        # 设置曾经购买的产品列表
        id = obj.getValue(obj.COL_ID)
        self.lcHistory.refresh({'peerId':id})
        
        # 设置消费记录
        #TODO
    
    def loadBill(self, billId):
        # 该处代码使用fetch获取object，导致该对象update时CDataSaleOrder.m_dataList中的缓存没有更新
        # 也就是说只有使用fetch获取db数据的才是新数据，从m_dataList中获取的是过时数据
        # 编辑功能都要注意检查这个问题
        #sql = "id='%s'" %billId
        #objs = CDataPurOrder.fetch(sql)
        #if (len(objs) != 1):
        #    print 'Error incorrect saleId:%s' %billId        
        #billObj = objs[0]
        
        self.m_billObj = CDataPurOrder.findObj(billId)        
        billObj = self.m_billObj
        
        billId = billObj.getValue(billObj.COL_ID)
        peerId = billObj.getValue(billObj.COL_PEERID)
        peerObj = CDataSupplier.getFirstInstance({CDataSupplier.COL_ID:peerId})
        
        self.setSelectPeer(peerObj)
        
        self.TSOID.SetLabel(billId)
        self.TSOID.Show()

        date = billObj.getValue(billObj.COL_BILLDATE)
        self.dateSO.SetValue(wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0))

        self.tcYingShou.SetValue(str(billObj.getValue(billObj.COL_TOTAL)))

        self.tcShiShou.SetValue(str(billObj.getPaid()))

        self.tcYouHui.SetValue(str(billObj.getValue(billObj.COL_DISCOUNT)))
        
        #COL_HANDLERID,
        #COL_RECOREDERID,
        hId = billObj.getValue(billObj.COL_HANDLERID)
        hObj = CDataStaff.getFirstInstance({CDataStaff.COL_ID:hId})
        self.cbHandler.SetValue(hObj.getValue(CDataStaff.COL_NAME))
        
        self.tcMemo.SetValue(billObj.getValue(billObj.COL_MEMO))
    
    def loadBillDetail(self, billId):
        '''把销售产品明细显示到grid'''
        self.appendGrid(CDataPurOrder.getProDetail(billId))
    
    def setEditBill(self, billId):
        '''设置要编辑的订单数据'''
        self.curState = self.STATE_MODIFY
        
        self.editedBillId = billId
        self.loadBill(billId)
        self.loadBillDetail(billId)
    
    def getGridData(self):
        '''return - [[id,name,spec,unit,cnt,price,total],[...]]'''
        proOnsale = []
        for row in range(self.gridSOProList.GetNumberRows()):
            dataRow = []
            for col in range(self.gridSOProList.GetNumberCols()): 
                dataRow.append(self.gridSOProList.GetCellValue(row, col))

            proOnsale.append(dataRow)
            
        return proOnsale
    
    def appendGrid(self, dataList):
        '''dataList - [[id,name,spec,unit,cnt,price,total],[...]]'''
        print dataList
        grid = self.gridSOProList
        for i in range(len(dataList)):
            row = grid.GetNumberRows()
            grid.AppendRows()
            for col in range(len(dataList[0])):
                grid.SetCellValue(row, col, kit.myStr(dataList[i][col]))
        
        # 添加新数据后，自动重新计算总金额                    
        self.refreshAmount()
    
    def saveBill(self):
        #billId = self.TSOID.GetLabel()
        if(self.isModify()):
            #billId = self.TSOID.GetLabel()
            billId = self.m_billObj.getValue(self.m_billObj.COL_ID)
        else:
            id,billId = CDataPurOrder.generateId(self.dateSO.GetValue().Format('%Y%m%d'))

        supId = self.m_peer.getValue(self.m_peer.COL_ID)
        
        # 把unicode转换为date类型，以免编辑出错
        # 以前使用fetch没用缓存，所以没发现这个错误
        # 思考：应该由界面控制dataModle<->view的数据类型转换还是由dataModle控制？
        # 应该是界面控制好一些，因为不同的view知道底层数据是什么样子的，而data不知道view会做成什么样子
        billDate = kit.str2Date(self.dateSO.GetValue().Format('%Y-%m-%d'))
        #billDate = self.dateSO.GetValue().Format('%Y-%m-%d')
        
        total = float(self.tcYingShou.GetValue())
        paid = float(self.tcShiShou.GetValue())
        discount = float(self.tcYouHui.GetValue())
        unpaid = total - paid - discount
        
        handlerId = self.cbHandler.getSelectObj().getValue(CDataStaff.COL_ID)
        recorderId = config.Cfg.getCurUser().getValue(CDataStaff.COL_ID) 
        
        memo = self.tcMemo.GetValue()
        
        data = {CDataPurOrder.COL_ID:billId, 
                CDataPurOrder.COL_PEERID:supId, 
                CDataPurOrder.COL_BILLDATE:billDate,
                CDataPurOrder.COL_WHID:1, 
                CDataPurOrder.COL_TOTAL:total, 
                #CDataPurOrder.COL_PAID:paid,
                CDataPurOrder.COL_DISCOUNT:discount, 
                CDataPurOrder.COL_HANDLERID:handlerId, 
                CDataPurOrder.COL_RECOREDERID:recorderId, 
                CDataPurOrder.COL_MEMO:memo}
        
        if(self.isModify()):
            self.m_billObj.setMulFieldVal(data)
            ret = self.m_billObj.update()
            if ret == 0:
                print(u'update返回值为0，可能是数据没有修改（销售单有个修改日期，必然修改），如果出现问题，在修改')
                ret = 1
            return ret
        else:
            self.m_billObj = CDataPurOrder.factory()
            self.m_billObj.setMulFieldVal(data)
            return self.m_billObj.insert()
        
    def saveDetail(self):
        for i in range(self.gridSOProList.GetNumberRows()):
            billId = self.m_billObj.getValue(self.m_billObj.COL_ID)

            peerId = self.m_peer.getValue(self.m_peer.COL_ID)
            
            proId = self.gridSOProList.GetCellValue(i, self.COL_PROID)
            proName = self.gridSOProList.GetCellValue(i, self.COL_PRONAME)
            unit = self.gridSOProList.GetCellValue(i, self.COL_UNIT)
            num = self.gridSOProList.GetCellValue(i, self.COL_CNT)
            price = self.gridSOProList.GetCellValue(i, self.COL_PRICE)
            total = self.gridSOProList.GetCellValue(i, self.COL_TOTAL)
            memo = self.gridSOProList.GetCellValue(i, self.COL_MEMO)
               
            data = {CDataPurDetail.COL_BILLID:billId, 
                CDataPurDetail.COL_PEERID:peerId, 
                CDataPurDetail.COL_PROID:proId,
                CDataPurDetail.COL_PRONAME:proName,
                CDataPurDetail.COL_UNIT:unit,
                CDataPurDetail.COL_NUM:num, 
                CDataPurDetail.COL_PRICE:price, 
                CDataPurDetail.COL_TOTAL:total,
                CDataPurDetail.COL_MEMO:memo}
                
            item = CDataPurDetail.factory(False)
            item.setMulFieldVal(data)
            cnt = item.insert()
            if(cnt <= 0):
                return cnt
        
        return 1    
    
    def disableEdit(self):
        self.TCCustomer.Disable()
        self.gridSOProList.Disable()
        self.tcMemo.Disable()
        self.dateSO.Disable()
        self.comboBox_staff.Disable()
        self.tcYouHui.Disable()
        
        self.btnSave.Disable()
    
    def OnGridRightUp(self, event):
        '''右键菜单弹出'''
        self.gridSOProList.GetGridWindow().PopupMenu(self.menu, event.GetPosition())
    
    def OnMenuAdd(self, event):
        '''右键菜单选中<添加已有商品>'''
        dlg = DlgSelectPro.create(self.GetParent(), DlgSelectPro.TypePurchase, self.m_peer)

        dlg.appendProDetail(self.getGridData())                    
        if(dlg.ShowModal() == wx.ID_OK):
            numRows=self.gridSOProList.GetNumberRows()
            if(numRows > 0):
                self.gridSOProList.DeleteRows(numRows=numRows)
            self.appendGrid(dlg.getProSaleList())
        
    def OnMenuNewPro(self, event):
        '''右键菜单选中<添加新商品>'''
        import DlgEditPro
        dlg = DlgEditPro.create(self)
        if (dlg.ShowModal() == wx.ID_OK):
            proObj = dlg.getProObj()
            
            proId = proObj.getValue(proObj.COL_ID)
            proName = proObj.getValue(proObj.COL_NAME)
            unit = proObj.getValue(proObj.COL_UNIT1)
            cnt = 0.0
            price = proObj.getValue(proObj.COL_DEFSALE1)
            total = kit.myFloat(cnt) * kit.myFloat(price)
            self.appendGrid([[proId, proName, unit, cnt, price,total]])
        
            self.gridSOProList.SetFocus()
            row = self.gridSOProList.GetNumberRows() - 1
            self.gridSOProList.SetGridCursor(row, self.COL_CNT)
            
    def OnMenuDelRow(self, event):
        '''右键菜单选中<删除选中行>'''
        rows = self.gridSOProList.GetSelectedRows()
        rows.sort(reverse=True)
        for index in range(len(rows)):
            self.gridSOProList.DeleteRows(rows[index])
        # 避免可能的多个选中导致的循环删除时错删
        #self.gridSOProList.DeleteRows(rows[0])
        self.refreshAmount()
                        
    def OnDateChanged(self, event):
##        if (self.isModify()):
##            msg = u'改变日期会导致单据编号发生变化，原来针对此订单的收款等信息将丢失，'\
##                    u'是否继续修改？'
##            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
##            if(dlg.ShowModal() == wx.ID_NO):
##                return
            
        self.refreshBillId()

    def OnBtnShowCustomerButton(self, event):
        self.tcPeer.resetPopupWinPos()
        self.pWin.Show()

    def OnLcHistoryProLeftDclick(self, event):
        item = self.lcHistory.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if (item == -1):
            return
            
        proId,proName,proSpec,unit,price = self.lcHistory.getProSaleInfo(item)
        self.appendGrid([[proId, proName,proSpec, unit, 0.0, price, 0.0]])
##        dlg = DlgProGX.create(self)
##        dlg.setData(proId=proId, unit=unit, price=price)
##        
##        if (dlg.ShowModal() == wx.ID_OK):
##
##            unit = dlg.unit
##            cnt = dlg.cnt
##            price = dlg.price
##            total = dlg.cnt*dlg.price
##            data = []
##            data.append([str(proId), proName, unit, str(cnt), str(price), str(total)])
##            
##            for unit,cnt in dlg.lonelyUnit.items():
##                data.append([str(proId), proName, unit, str(cnt), 0.0, 0.0])
##            
##            self.appendGrid(data)
            
    def OnGridSOProListGridCellChange(self, event):
        '''改变<单价><数量>时，重新计算<小计><应收金额>'''
        #print 'OnGridSOProListGridCellChange'
        if (event.GetCol() < self.COL_CNT):
            #cnt\price unchanged
            return
        
        if (event.GetCol() == self.COL_TOTAL):
            msg = u'统计金额不允许修改，请调整单价或设置优惠金额'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
        
        grid = self.gridSOProList
        try:
            row = event.GetRow()
            total = float(grid.GetCellValue(row, self.COL_CNT)) * \
                        float(grid.GetCellValue(row, self.COL_PRICE))
            grid.SetCellValue(row, self.COL_TOTAL, str(total))
        
            self.refreshAmount()
            
        except ValueError,e:
            print e
            dlg = wx.MessageDialog(self, u'输入错误：请输入数值',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            # 150125 - 会导致错误循环
            #grid.SetGridCursor(row, event.GetCol())

    def OnGridSOProListGridSelectCell(self, event):
        self.gridSOProList.SelectRow(event.GetRow())
        # 必须保留，以便选中Cell可以进入可编辑状态
        event.Skip()

    def OnGridSOProListGridCellRightClick(self, event):
        self.gridSOProList.SelectRow(event.GetRow())

    def checkProStock(self):
        import DlgProMulUnitAdjust
        #print 'checkProStock'
        list = []
        grid = self.gridSOProList
        for i in range(grid.GetNumberRows()):
            proId = int(grid.GetCellValue(i, self.COL_PROID))
            proName = grid.GetCellValue(i, self.COL_PRONAME)
            unit = grid.GetCellValue(i, self.COL_UNIT)
            proObj = CDataProduct.findObj(proId)
            for val in proObj.getUnratioUnit(unit):
                list.append([proId, proName,val])
        
        #print list
        if list:
            dlg = DlgProMulUnitAdjust.DlgProMulUnitAdjust(self, True)
            dlg.appendData(list)
            dlg.ShowModal()
            
    def OnBtnSaveButton(self, event):
        '''保存订单'''
        if (self.m_peer is None):
            dlg = wx.MessageDialog(self, u'订单未完成：请选择供应商',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        if (self.gridSOProList.GetNumberRows() <= 0):
            dlg = wx.MessageDialog(self, u'订单未完成：未选择产品',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        try:
            dbmngr.dbmngr.beginTrans()
            
            if (self.isModify()):
                CDataPurOrder.clearDetail(self.editedBillId)
                #assert self.editedBillId == self.TSOID.GetLabel()
                #CDataPurOrder.deleteBill(self.editedBillId, False)
                #assert self.editedBillId == self.TSOID.GetLabel()
##                if (self.editedBillId != self.TSOID.GetLabel()):
##                    detachFund = True
##                    msg = u'由于订单日期修改，订单ID发生变化，原来针对此订单的收款等信息将丢失，'\
##                            u'是否继续修改？'
##                    
##                else:
##                    detachFund = False
##                    msg = u'修改订单，原来针对此订单的收款等信息有可能出现不一致情况，'\
##                            u'是否继续修改？'
##                            
##                dlg = wx.MessageDialog(self, msg, u'提示', wx.YES_NO|wx.ICON_QUESTION)
##                if(dlg.ShowModal() == wx.ID_NO):
##                    return
##                
##                CDataPurOrder.deleteBill(self.editedBillId, detachFund)
            
            #update没有改动任何项的话会返回0,saleorder因为有时间因素必然会修改    
            #if(self.saveBill() <= 0): 
            if(self.saveBill() < 0):
                msg = u'订单保存失败，请查找原因！'
                #dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
                #dlg.ShowModal()
                #return
                raise Exception(msg)
            
            if(self.saveDetail() <= 0):
                msg = u'产品明细保存失败，请查找原因！'
                #dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
                #dlg.ShowModal()
                #return
                raise Exception(msg)
            
            # 150502 - 在选择产品时，设置多单位
            #self.checkProStock()
        
            dbmngr.dbmngr.commitTrans()
            
        except Exception as e:
            dbmngr.dbmngr.rollbackTrans(e)
            self.bSaved = False
        
        else:        
            self.disableEdit()
            self.bSaved = True
    
    def quit(self,  doQuit=True):
        if doQuit:        
            book = self.GetParent()
            book.DeletePage(book.GetSelection())
        return True
    
    def doClose(self,  doQuit=True):
        return self.close(doQuit)
        
    def close(self,  doQuit=True):
        if not (self.bSaved):
            if (self.curState == self.STATE_MODIFY):
                msg = u'订单没有保存，退出后修改的内容将不会保存，是否继续退出?'
            else:
                msg = u'订单没有保存，退出后将丢失当前数据，是否继续退出?'
            dlg = wx.MessageDialog(self, msg,u'提示',wx.YES_NO|wx.ICON_QUESTION)
            if(dlg.ShowModal() == wx.ID_NO):
                return False

        return self.quit(doQuit)
        
    def OnBtnCancelButton(self, event):
        self.close()

    def OnBtnHistoryButton(self, event):
        pass
        
        
